package org.kent.w.base.common.executor;

import org.apache.commons.lang3.StringUtils;
import org.kent.w.base.common.constant.CommonConstants;
import org.slf4j.MDC;

/**
 * 可跟踪的Runnable
 *
 * @author wu.jigang@geely.com
 * @version 1.0
 * @Date :Created by 2020/3/6.
 */
public abstract class TraceableRunnable implements Runnable {

    private String traceId;

    public TraceableRunnable() {
        this.traceId = MDC.get(CommonConstants.MDC_TRADE_ID);
    }

    /***
     * 会话ID追加
     * @return
     */
    protected void beforeTrace() {

        if (StringUtils.isNotBlank(traceId)) {
            MDC.put(CommonConstants.MDC_TRADE_ID, traceId);
        }
    }

    /***
     * 会话ID追加
     * @return
     */
    protected void afterTrace() {

        if (StringUtils.isNotBlank(traceId)) {
            MDC.remove(CommonConstants.MDC_TRADE_ID);
        }
    }

    @Override
    public void run() {

        beforeTrace();

        try {

            process();

        } finally {
            afterTrace();
        }
    }

    public abstract void process();

}
